package com.learn.boot.datasource.aspect;

import com.learn.boot.datasource.config.DataSourceContextHolder;
import com.learn.boot.datasource.annotation.DS;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @description:    java类作用描述
 * @author:         MI
 * @email:          448341911@qq.com
 * @createTime:     2023/12/16 13:02
 * @updateUser:     cong zhi
 * @updateTime:     2023/12/16 13:02
 * @updateRemark:   修改内容
 * @version:        v1.0
 */
@Aspect
@Component
public class DSAspect {

    @Pointcut("@annotation(com.learn.boot.datasource.annotation.DS)")
    public void dynamicDataSource() {

    }

    @Around("dynamicDataSource()")
    public Object datasourceAround(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature)point.getSignature();
        Method method = signature.getMethod();
        DS ds = method.getAnnotation(DS.class);
        if (Objects.nonNull(ds)){
            DataSourceContextHolder.setDataSource(ds.value());
        }
        try {
            return point.proceed();
        } finally {
            DataSourceContextHolder.removeDataSource();
        }
    }
}
